package com.huajin.iot.system.controller;

import com.huajin.iot.common.annotation.Log;
import com.huajin.iot.common.controller.BaseController;
import com.huajin.iot.common.domain.FileDO;
import com.huajin.iot.common.domain.Tree;
import com.huajin.iot.common.service.FileService;
import com.huajin.iot.common.utils.MD5Utils;
import com.huajin.iot.common.utils.R;
import com.huajin.iot.common.utils.ShiroUtils;
import com.huajin.iot.system.domain.MenuDO;
import com.huajin.iot.system.service.MenuService;
import com.huajin.iot.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = {"登录接口"})
@RestController
public class LoginController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MenuService menuService;
    @Autowired
    FileService fileService;
    @Autowired
    UserService userService;

    @ApiOperation("测试服务，欢迎页")
    @GetMapping({"/", ""})
    R welcome() {
        return R.ok("Welcome");
    }
    // TODO: 2018/10/11  增加验证码的获取和验证2个方法


    @ApiOperation("验证用户名和密码")
    @Log("登录，验证用户名和密码")
    @PostMapping("/login")
    @ResponseBody
    R login(String username, String password) {
        password = MD5Utils.encrypt(username, password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        R r = new R();
        try {
            subject.login(token);
            //@todo 暂定在此处查找该user的登陆次数，判定是否第一次登陆。
            Map<String, Object> userPasswordMap = new HashMap<>();
            userPasswordMap.put("username", username);
            userPasswordMap.put("password", password);
            int userLoginStatus = userService.list(userPasswordMap).get(0).getStatus();
            if (userLoginStatus == 0) {
                r.put("userStatus", 3);
                return r;
            }
            //todo 修改该用户的状态未正常。
            return R.ok();
        } catch (AuthenticationException e) {
            return R.error("用户或密码错误");
        }
    }


    @ApiOperation("登录成功转向首页")
    @Log("登录成功，请求访问主页")
    @GetMapping("/index")
    R index() {
        List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());
        Map<String, Object> resultMap = new HashMap();
        resultMap.put("menus", menus);
        resultMap.put("userid", getUserId());
        resultMap.put("name", getUser().getName());
     /*   FileDO fileDO = fileService.get(getUser().getPicId());
        if (fileDO != null && fileDO.getUrl() != null) {
            if (fileService.isExist(fileDO.getUrl())) {
                model.addAttribute("picUrl", fileDO.getUrl());
            } else {
                model.addAttribute("picUrl", "/img/photo_s.jpg");
            }
        } else {
            model.addAttribute("picUrl", "/img/photo_s.jpg");
        }*/
        resultMap.put("username", getUser().getUsername());
        return R.ok(resultMap);
    }

    @ApiOperation("退出系统")
    @Log("退出系统")
    @GetMapping("/logout")
    R logout() {
        ShiroUtils.logout();
        return R.ok();
    }

}
